package org.jackysoft.file;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.jdbc.Work;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

public class CleanFileWork implements Work {

	protected final Log log = LogFactory.getLog(CleanFileWork.class);
	public int year;
	public int month;
	public final Set<String> paths = Sets.newHashSet();
	private List<String> sqlBatch = Lists.newArrayList();

	@Override
	public void execute(Connection connection) throws SQLException {
		String[] tables = new String[] { "UploadedFileItem", "ReceivedFileItem" };
		for (String table : tables) {
			fetchFile(table, connection);
		}
		Statement stat = connection.createStatement();
		for (String sql : sqlBatch)
			stat.addBatch(sql);
		int[] ri = stat.executeBatch();
		log.info("删除了 " + ri.length + " 条记录");
	}

	void fetchFile(String table, Connection connection) throws SQLException {
		String sql = "select f.id,f.realName,f.createTime from " + table
				+ " f where year(f.createTime)<=? and month(f.createTime)<=?";
		PreparedStatement pstat = connection.prepareStatement(sql);
		pstat.setInt(1, year);
		pstat.setInt(2, month);
		ResultSet rset = pstat.executeQuery();
		while (rset.next()) {
			String id = rset.getString(1);
			sqlBatch.add("delete from " + table + " where id='" + id + "'");
			String realName = rset.getString(2);
			Date date = rset.getDate(3);
			paths.add(realName);
			log.info("处理文件 [" + id + "] " + realName + " AT " + date.toString());
		}
	}


}
